package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.model.Review;
import com.example.myapplication.model.Course;
import com.example.myapplication.model.Teacher;
import com.example.myapplication.db.DBManager;
import java.util.ArrayList;

public class CourseDetailActivity extends AppCompatActivity {
    private TextView textViewCourseName, textViewTeacherName, textViewCourseInfo;
    private TextView textViewAverageRating;
    private RatingBar ratingBarAverage;
    private ListView listViewReviews;
    private Button buttonAddReview;
    private Button buttonSortByTime;
    private Button buttonSortByLikes;
    private ArrayList<Review> reviewList;
    private String courseName;
    private String teacherName;
    private DBManager.ReviewSortType currentSortType = DBManager.ReviewSortType.TIME_DESC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);

        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("课程详情");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setElevation(4);
        }

        // 初始化视图
        textViewCourseName = findViewById(R.id.textViewCourseName);
        textViewTeacherName = findViewById(R.id.textViewTeacherName);
        textViewCourseInfo = findViewById(R.id.textViewCourseInfo);
        listViewReviews = findViewById(R.id.listViewReviews);
        buttonAddReview = findViewById(R.id.buttonAddReview);
        ratingBarAverage = findViewById(R.id.ratingBarAverage);
        textViewAverageRating = findViewById(R.id.textViewAverageRating);
        buttonSortByTime = findViewById(R.id.buttonSortByTime);
        buttonSortByLikes = findViewById(R.id.buttonSortByLikes);

        // 获取传递的课程名和老师名
        courseName = getIntent().getStringExtra("courseName");
        teacherName = getIntent().getStringExtra("teacherName");
        
        if (courseName != null) {
            textViewCourseName.setText(courseName);
        }
        if (teacherName != null) {
            textViewTeacherName.setText(teacherName);
        }

        // 可选：从数据库获取课程详细信息
        DBManager dbManager = new DBManager(this);
        if (courseName != null && teacherName != null) {
            Teacher teacher = dbManager.getTeacherByCourseName(courseName);
            if (teacher != null) {
                textViewTeacherName.setText(teacher.getName());
                textViewCourseInfo.setText(teacher.getInfo());
            }
        }

        // 设置添加评论按钮点击事件
        buttonAddReview.setOnClickListener(v -> {
            Intent intent = new Intent(CourseDetailActivity.this, AddReviewActivity.class);
            intent.putExtra("courseName", courseName);
            startActivity(intent);
        });

        // 设置排序按钮点击事件
        buttonSortByTime.setOnClickListener(v -> {
            if (currentSortType == DBManager.ReviewSortType.TIME_DESC) {
                currentSortType = DBManager.ReviewSortType.TIME_ASC;
                buttonSortByTime.setText("最早");
            } else {
                currentSortType = DBManager.ReviewSortType.TIME_DESC;
                buttonSortByTime.setText("最新");
            }
            updateSortButtonsState();
            loadReviews();
        });

        buttonSortByLikes.setOnClickListener(v -> {
            if (currentSortType == DBManager.ReviewSortType.LIKES_DESC) {
                currentSortType = DBManager.ReviewSortType.LIKES_ASC;
                buttonSortByLikes.setText("最冷");
            } else {
                currentSortType = DBManager.ReviewSortType.LIKES_DESC;
                buttonSortByLikes.setText("最热");
            }
            updateSortButtonsState();
            loadReviews();
        });

        loadReviews();
        updateSortButtonsState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadReviews();
    }

    private void updateSortButtonsState() {
        buttonSortByTime.setAlpha(isSortingByTime() ? 1.0f : 0.6f);
        buttonSortByLikes.setAlpha(isSortingByLikes() ? 1.0f : 0.6f);
    }

    private boolean isSortingByTime() {
        return currentSortType == DBManager.ReviewSortType.TIME_DESC || 
               currentSortType == DBManager.ReviewSortType.TIME_ASC;
    }

    private boolean isSortingByLikes() {
        return currentSortType == DBManager.ReviewSortType.LIKES_DESC || 
               currentSortType == DBManager.ReviewSortType.LIKES_ASC;
    }

    private void loadReviews() {
        if (courseName == null) return;
        
        DBManager dbManager = new DBManager(this);
        reviewList = dbManager.getReviewsByCourseName(courseName, currentSortType);
        ReviewAdapter adapter = new ReviewAdapter(this, reviewList);
        listViewReviews.setAdapter(adapter);

        updateAverageRating();
    }

    private void updateAverageRating() {
        if (reviewList == null || reviewList.isEmpty()) {
            ratingBarAverage.setRating(0);
            textViewAverageRating.setText("暂无评分");
            return;
        }

        float totalRating = 0;
        for (Review review : reviewList) {
            totalRating += review.getRating();
        }
        float averageRating = totalRating / reviewList.size();

        ratingBarAverage.setRating(averageRating);
        textViewAverageRating.setText(String.format("%.1f", averageRating));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
